const { default: axios } = require("axios");
const { params, api } = require("./src/config/config");
const { getToken } = require("./src/getToken/index");
const { sendMessage } = require("./src/sendMessage/index");
const moment = require("moment");
moment.locale("zh-cn");

// 模板消息
const message = {
  nowDate: "2025年01月01日 星期一",
  city: "武汉",
  weather: "晴",
  low: "0°C",
  high: "99°C",
  loveDate: "365",
  txt1: "",
  txt2: "",
};

const start = async () => {
  let access_token = await getToken(params);

  message.nowDate = moment().format("YYYY年MM月DD日 dddd");
  message.loveDate = moment().diff(moment(api.love), "days");

  // 请求天气预报信息
  await axios
    .get(
      `https://api.map.baidu.com/weather/v1/?district_id=${api.district_id}&data_type=all&ak=${api.ak}`
    )
    .then((res) => {
      if (res.status === 200) {
        message.city = res.data.result.location.city;
        message.weather = res.data.result.forecasts[0].text_day;
        message.low = res.data.result.forecasts[0].low + "°C";
        message.high = res.data.result.forecasts[0].high + "°C";
      }
    });

  // 请求情话信息
  await axios
    .get(`https://apis.tianapi.com/saylove/index?key=${api.key}`)
    .then((res) => {
      if (res.status === 200) {
        const txt = res.data.result.content;
        message.txt1 = txt.slice(0, 20);
        message.txt2 = txt.slice(20) || "❤️";
        console.log(txt);
      }
    });

  sendMessage({
    access_token,
    ...params,
    data: {
      nowDate: {
        value: message.nowDate,
      },
      city: {
        value: message.city,
      },
      weather: {
        value: message.weather,
      },
      low: {
        value: message.low,
      },
      high: {
        value: message.high,
      },
      loveDate: {
        value: message.loveDate,
      },
      txt1: {
        value: message.txt1,
      },
      txt2: {
        value: message.txt2,
      },
    },
  });
};

const run = async () => {
  await start();
  setTimeout(run, 86400000 - (Date.now() % 86400000)); // 对齐整点
};
run();
